package com.ebocy.hammer.core.service;

import java.util.Map;

import org.apache.log4j.Logger;

import com.ebocy.hammer.core.GameCache;
import com.ebocy.hammer.core.db.DaoManager;
import com.ebocy.hammer.core.db.IDao;
import com.ebocy.hammer.core.domain.GamePlayer;
import com.ebocy.hammer.core.domain.Room;
import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.message.AbstractS2CMessage;
import com.ebocy.hammer.core.message.S2CExitGameMessage;

/**
 * 玩家对象的操作
 * 
 * @author HouQingrong Jun 9, 2012
 */
public class GamePlayerService {
	protected static Logger logger = EbocyLogManager.getSystemLogger();
	private IDao<GamePlayer> dao;

	@SuppressWarnings("unchecked")
	private GamePlayerService() {
		dao = DaoManager.getInstance().getDao(GamePlayer.class);
	}

	public static GamePlayerService getInstance() {
		return SingletonClassInstance.instance;
	}

	/**
	 * 构造线程安全的单例模式
	 */
	private static class SingletonClassInstance {
		private static final GamePlayerService instance = new GamePlayerService();
	}

	/**
	 * 更新用户信息
	 * 
	 * @param gamePlayer
	 * @param value
	 */
	public void updateGamePlayer(GamePlayer gamePlayer, Map<?, ?> values) {
		dao.update(gamePlayer.getId(), values);
	}

	public GamePlayer getGamePlayerById(long gamePlayerId) {
		return dao.findOne(GamePlayer.GAMEPLAYERID, gamePlayerId);
	}

	/**
	 * 退出游戏
	 */
	public void exitGame(GamePlayer gamePlayer) {
		if (gamePlayer != null) {
			// 从缓存中去掉玩家记录
			GameCache.getInstance().removeGamePlayer(gamePlayer);
			Room room = GameCache.getRoom(gamePlayer.getRoomId());
			if (room != null) {
				logger.info("    " + gamePlayer.getName() + "从房间" + room.roomId + "中退出");
				switch (room.state) {
				/**
				 * world服务器,房间创建状态,如果房间中worlds 列表为空,则删除房间
				 */
				case 0:
					//状态0下,维持房间内组队玩家列表
					room.delWorld(gamePlayer.getGamePlayerId());
					break;
					/**
					 * battle服务器,战斗房间初始化状态,
					 * 战斗未开始,有玩家离线,在losts列表中增加玩家id,用来判断房间是否可以进入战斗
					 */
				case 1:
					//状态1下,维持房间内玩家列表
					room.delBattle(gamePlayer.getGamePlayerId());
					//状态1下,离线玩家列表
					room.addLost(gamePlayer.getGamePlayerId());
					break;
					/**
					 * // battle,战斗开始状态
					 */
				case 2:
					room.delBattle(gamePlayer.getGamePlayerId());
					break;
				}
				// 通知其他玩家
				AbstractS2CMessage message = new S2CExitGameMessage(gamePlayer.getGamePlayerId());
				gamePlayer.sendMessageToRoomOther(message);
				GameCache.getInstance().delCache(gamePlayer.getGamePlayerId());
			}
		}
	}

}
